package com.gd.controller;

import com.gd.pojo.User;
import com.gd.service.UserService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;
import java.util.UUID;


@Controller
@RequestMapping("/user")
//这里用了@SessionAttributes，可以直接把model中的user(也就key)放入其中
//这样保证了session中存在user这个对象
@SessionAttributes("user")
public class UserContoller {

    @Autowired
    private UserService userServivce;

    //正常访问login页面
    @RequestMapping("/login")
    public String login(User user, HttpSession session) {
        session.setAttribute("USER_SESSION" ,user);
        return "login";
    }


    //表单提交过来的路径
    @RequestMapping("/checkLogin")
    public String checkLogin(User user, Model model, HttpSession session) {
        //调用service方法
        user = userServivce.checkLogin(user.getUsername(), user.getPassword());
        //若有user则添加到model里并且跳转到成功页面
        if (user != null) {
            model.addAttribute("user", user);
            session.setAttribute("USER_SESSION" ,user);
            System.out.println(user);
            /* return "allPaper";*/
            //从User跳转到Paper控制器 直接写allpaper会导致页面无数据
            return "redirect:/paper/allPaper";
        }
        return "login";
    }
    @RequestMapping("/filetest")
    public String filetest() {
        return "fileUpload";
    }
    /**
     * Web上传方式  使用web上传 需要将SpringMVC配置器里面的解析器注释掉 不然List为0
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/filenb")
    public String FileUpload(HttpServletRequest request) throws Exception {
        //使用Fileupload組件完成上传
        //上传的位置
        String path = request.getSession().getServletContext().getRealPath("/FileTest/");
        System.out.println(path);
        //判断文件是否存在 如果不存在 创建该文件夹
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        //解析request对象 ，获取上传文件项
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        //解析request
        List<FileItem> fileItems = upload.parseRequest(request);
        //遍历
        for (FileItem item : fileItems) {
            //进行判断，当前items是否为文件上传
            if (item.isFormField()) {
                //说明普通表单项
            } else {
                //说明上传文件项
                //获取上传文件名称
                String filename = item.getName();
                System.out.println(filename);
                //完成文件上传
                item.write(new File(path, filename));
                //删除缓存
                item.delete();
                return "success";
            }
        }

        return "fail";

    }

    /**
     * SpringMVC上传方式
     *
     * @param request
     * @param FileUpload
     * @return
     * @throws Exception
     */
    @RequestMapping("/fileMVC")
    public String FileUpload2(HttpServletRequest request, MultipartFile FileUpload, @RequestParam("name") String name) throws Exception {
        //使用Fileupload組件完成上传
        //上传的位置
        String path = request.getSession().getServletContext().getRealPath("/FileTest/");
        System.out.println(path);
        //判断文件是否存在 如果不存在 创建该文件夹
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        //获取上传文件名称
        String filename = FileUpload.getOriginalFilename();
        String filename2=name+"_"+ UUID.randomUUID()+"_"+filename;
        if (filename != null) {
            //完成文件上传
            FileUpload.transferTo(new File(path, filename2));
            return "success";
        }

        return "fail";

    }

    /**
     * 文件下载
     * @param request
     * @param filename
     * @return
     * @throws Exception
     */
    @RequestMapping("/download")
    public ResponseEntity<byte[]> fileDownload(HttpServletRequest request, String filename ) throws Exception{
        //制定下载文件的路径
        String path=request.getServletContext().getRealPath("/FileTest");
        //创建该文件对象
        File file=new File(path+ File.separator+filename);
        //设置响应头
        HttpHeaders headers=new HttpHeaders();
        //通知浏览器以下载方式打开浏览器
        headers.setContentDispositionFormData("attachment" ,filename);
        //定义以流的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //使用SpringMVC框架的ResponseEntity对象封装返回下载数据
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);

    }
/*    //测试超链接跳转到另一个页面是否可以取到session值
    @RequestMapping("/anotherpage")
    public String hrefpage(){

        return "anotherpage";
    }*/

    //注销用户

   /* @RequestMapping("/outLogin")
    public String outLogin(HttpSession session){
        //通过session.invalidata()方法来注销当前的session
        session.invalidate();
        return "login";
    }*/

    //注册
    @RequestMapping("/regist")
    public String regist() {
        return "regist";
    }

    //注册成功静如主页面
    @RequestMapping("/doRegist")
    public String doRegist(User user, Model model) {
        System.out.println(user.getUsername());
        //写入数据库
        userServivce.Regist(user);
        return "forward:/paper/allPaper";
    }
}
